﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MDM.GUI.MDM.DataAccess;
using System.IO;
using MDM.GUI.MDM.DataObjects;
using System.Management;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.Win32;

namespace MDM.GUI.MDM.Business
{
    public delegate void DoProcess(string fileName);
    class ModuleManager     
    {


        /// <summary>
        /// Start: Phan LoadModuleList, dùng để đọc file thống kê (installed.xml) và load danh sách các module cũng như thông tin module lên giao diện.
        /// </summary>
        public static void LoadModuleList()
        {
            ModuleIO.LoadModuleList();
        }
        /// <summary>
        /// End: Phan LoadModuleList
        /// </summary>







        /// <summary>
        /// Start: Phan ValidateModule
        /// </summary>
        public static bool ValidateModule(string modName)
        {

            //load version file here
            ModuleIO.LoadVersionXML(Common.sModulePath + @"\" + Common.sVersionXmlName);
            foreach (ModuleInfor mod in Common.aModInfor)
            {
                if (mod.Name == modName)
                    return false;
            }
            return true;
        }
        /// <summary>
        /// End: Phan ValidateModule
        /// </summary>














        /// <summary>
        /// Start: Phan Update Installed Module
        /// </summary>

        public static void UpdateInstalledModule(string sModuleName)
        {
            UnInstallModule(sModuleName);
            InstallNewModule();
        }


        /// <summary>
        /// End: Phan Update Installed Module
        /// </summary>

        //Doprocess
        public static event DoProcess DoProcessHandler;








        /// <summary>
        /// Start: Phan UnInstallModule
        /// </summary>

        public static void UnInstallModule(string sModuleName)
        {
            RemoveModule(sModuleName);
        }




        public static void RemoveModule(string sModuleName)
        {
            RemoveFile(sModuleName);
            RemoveNameModule(sModuleName);
        }




        public static void RemoveNameModule(string sModuleName)
        {

            // string strcurrent_path = AQFramework.Utilities.FileFolder.GetCurrentExePath();
            MDM.DataObjects.Installed itemModule = AQFramework.Utilities.Serializer<MDM.DataObjects.Installed>.Load(Common.sModuleDestinationPath + "\\installed.xml");
            foreach (MDM.DataObjects.Module itemMod in itemModule.Modules)
            {
                if (itemMod.Name == sModuleName)
                {
                    itemModule.Modules.Remove(itemMod);

                    break;
                }
            }
            AQFramework.Utilities.Serializer<MDM.DataObjects.Installed>.Save(itemModule, Common.sModuleDestinationPath + "\\installed.xml");
        }




   /*     public static void clearFolder(string FolderName)
        {
            DirectoryInfo dir = new DirectoryInfo(FolderName);

            foreach (FileInfo fi in dir.GetFiles())
            {
                fi.Delete();
            }

            foreach (DirectoryInfo di in dir.GetDirectories())
            {
                clearFolder(di.FullName);
                di.Delete();
            }
        }
        */


        public static void clearFile1(MDM.DataObjects.File itemTaptin, string strThuMucChuaFileCanXoa)
        {

            if (DoProcessHandler != null)
                DoProcessHandler(itemTaptin.Name);
            FileInfo fi = new FileInfo(strThuMucChuaFileCanXoa + "\\" + itemTaptin.Name);
            fi.Delete();
        }


        public static void clearFile2(MDM.DataObjects.File itemTaptin, string strThuMucChuaFileCanXoa, string strThuMucMeChuaFileCanXoa)
        {

            if (DoProcessHandler != null)
                DoProcessHandler(itemTaptin.Name);
            string sTmp = strThuMucChuaFileCanXoa + @"\" + strThuMucMeChuaFileCanXoa + @"\" + itemTaptin.Name;
            FileInfo fi = new FileInfo(sTmp);
            fi.Delete();
        }

        public static void RemoveFile(string sModuleName)
        {
            MDM.DataObjects.Installed itemModule = AQFramework.Utilities.Serializer<MDM.DataObjects.Installed>.Load(Common.sModuleDestinationPath + "\\installed.xml");
            foreach (MDM.DataObjects.Module itemMod in itemModule.Modules)
            {
                if (itemMod.Name == sModuleName)
                {
                    MDM.DataObjects.Version itemVersion = AQFramework.Utilities.Serializer<MDM.DataObjects.Version>.Load(Common.sModuleDestinationPath + "\\" + itemMod.VersionID+".xml");
                    foreach (MDM.DataObjects.File item in itemVersion.Installs.Files)
                    {
                        if (item.Modifier == "Owner")
                        {
                            if (item.Path == ".")
                            {
                                clearFile1(item, Common.sModuleDestinationPath);
                            }
                            clearFile2(item, Common.sModuleDestinationPath, item.Path);
                        }
                    }

                    FileInfo fiImage = new FileInfo(Common.sModuleDestinationPath +"\\"+ itemVersion.Images.Path);
                    fiImage.Delete();
                 
                    FileInfo fiVersion = new FileInfo(Common.sModuleDestinationPath + "\\" + itemMod.VersionID+".xml");                                    
                    fiVersion.Delete();
                }
            }
        }



        /// <summary>
        /// End: Phan UnInstallModule
        /// </summary>






        /// <summary>
        /// Start: Phan InstallNewModule
        /// </summary>

        public static void InstallNewModule()
        {
            MDM.DataObjects.Version itemVersion = AQFramework.Utilities.Serializer<MDM.DataObjects.Version>.Load(Common.sModulePath + "\\" + Common.sVersionXmlName);
     //       MDM.DataObjects.Installed itemModule = AQFramework.Utilities.Serializer<MDM.DataObjects.Installed>.Load(Common.sModuleDestinationPath + "\\installed.xml");


           
            foreach (MDM.DataObjects.File item in itemVersion.Installs.Files)
            {
                if (item.Path == ".")
                {
                    CopyFile2(item, Common.sModulePath, Common.sModuleDestinationPath, true);
                }
                else
                    CopyFile1(item, Common.sModulePath, Common.sModuleDestinationPath, true);

                
                
            }

            Common.GenerateID();
            FileInfo fiImage = new FileInfo(Common.sModulePath + "\\" + itemVersion.Images.Path);
            fiImage.CopyTo(Common.sModuleDestinationPath+"\\"+itemVersion.Images.Path, true);
            FileInfo fiVersion = new FileInfo(Common.sModulePath + "\\" + Common.sVersionXmlName);
            fiVersion.CopyTo(Common.sModuleDestinationPath + "\\" + Common.sVersionID+".xml", true);



            foreach (object item in itemVersion.Actions)
            {
                if (item is MDM.DataObjects.Registry)
                {
                    ActionManager.DoRegistry((MDM.DataObjects.Registry)item);
                }

                if (item is MDM.DataObjects.Dos)
                {
                    ActionManager.DoDos((MDM.DataObjects.Dos)item);

                }

                if (item is MDM.DataObjects.Window)
                {
                    ActionManager.DoWindow((MDM.DataObjects.Window)item);
                }

                /*          if (item is MDM.DataObjects.Service)
                          {
                              ActionManager.DoService((MDM.DataObjects.Service)item);
                          }

                          if (item is MDM.DataObjects.Shutdown)
                          {
                              ActionManager.DoShutdown();
                          }

                          if (item is MDM.DataObjects.Restart)
                          {
                              ActionManager.DoRestart();
                          }*/
            }

            MDM.DataAccess.ModuleIO.UpdateNewModule();
        }


      


        /*    public static Boolean CopyFile(MDM.DataObjects.File itemTaptin, string strThuMucNguonPath, string strdestPath)
            {
                //kiem tra

                //b1: create module folder
                //   createFolder( Common.sModuleDestinationPath, );
                //b2: create sub-folders
                //b3: copy files

                FileInfo fi = new FileInfo(strThuMucNguonPath + "\\" + itemTaptin.Path + "\\" + itemTaptin.Name);
                try
                {
                    fi.CopyTo(strdestPath + "\\" + itemTaptin.Path + "\\" + itemTaptin.Name);
                }
                catch (Exception ex)
                {
                    return false;
                }
                return true;
            }

            */


  /*     public static void CopyFile(MDM.DataObjects.File itemTaptin, string strThuMucNguonPath, string strdestPath)     
        {
            //Nhung: thong bao file copy
            if (DoProcessHandler != null)
                DoProcessHandler(itemTaptin.Name);
            FileInfo fi = new FileInfo(strThuMucNguonPath + "\\" + itemTaptin.Path + "\\" + itemTaptin.Name);
            fi.CopyTo(strdestPath + "\\" + itemTaptin.Path + "\\" + itemTaptin.Name);
        }
      */


        public static void CopyFile1(MDM.DataObjects.File itemTaptin, string strThuMucNguonPath, string strdestPath, Boolean bloverwrite)
        {
          
            if (DoProcessHandler != null)
                DoProcessHandler(itemTaptin.Name);
            FileInfo fi = new FileInfo(strThuMucNguonPath + "\\" + itemTaptin.Path + "\\" + itemTaptin.Name);
            fi.CopyTo(strdestPath + "\\" + itemTaptin.Path + "\\" + itemTaptin.Name, bloverwrite);
        }


        public static void CopyFile2(MDM.DataObjects.File itemTaptin, string strThuMucNguonPath, string strdestPath, Boolean bloverwrite)
        {
           
            if (DoProcessHandler != null)
                DoProcessHandler(itemTaptin.Name);
            FileInfo fi = new FileInfo(strThuMucNguonPath + "\\" + itemTaptin.Name);
            fi.CopyTo(strdestPath + "\\" + itemTaptin.Name,bloverwrite);
        }









        private static bool createFolder(String sPath, String sFolderName)
        {
            String sFolderPath = sPath + @"\" + sFolderName;
            DirectoryInfo folderTmp = new DirectoryInfo(sFolderPath);
            if (!folderTmp.Exists)
            {
                try
                {
                    folderTmp.Create();
                    return true;
                }
                catch (Exception)
                {
                    return false;
                }
            }
            return false;
        }










        private static bool copyFile(String sFileSource, String sFileDest)
        {
            FileInfo fileSrc = new FileInfo(sFileSource);
            if (fileSrc.Exists)
            {
                fileSrc.CopyTo(sFileDest);
            }
            return false;
        }


        /// <summary>
        /// End: Phan InstallNewModule
        /// </summary>






    }

}




